// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Text;
using System.Linq;

namespace SnapObjects.Data.Informix
{
    internal class InformixSqlFunctionStatementGenerator : SqlFunctionStatementGenerator
    {
        public InformixSqlFunctionStatementGenerator(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {
        }


        public override SqlSyntaxDescription Create(SqlStatement statement)
        {
            var function = (SqlFunctionStatement)statement;

            var tokens = this.SpliceStatement(function);

            var builder = new StringBuilder();
            builder.Append("call");
            builder.Append(SqlWhitespaceToken.Whitespace);
            foreach (var token in tokens)
            {
                if (token.Type == SqlTokenType.Identifier)
                {
                    builder.Append(_helper.DelimitIdentifier(token.Text));
                }
                else
                {
                    builder.Append(token.Text);
                }
            }

            var functionName = builder.ToString();

            var parameters = function.Parameters.ToDictionary(
                m => m.Key, m => _helper.GenerateParameterName(m.Key));

            this.CreateParameters(builder, statement);

            return new SqlSyntaxDescription(builder.ToString(), parameters, true);
        }
    }
}
